const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const path = require('path');
const { router: authRoutes, initDatabaseConnection } = require('./routes/auth.cjs');
const { router: fileRoutes, initDatabaseConnection: initFileDatabaseConnection } = require('./routes/file.cjs');
const peopleRoutes = require('./routes/people.cjs');
// const { router: userRoutes, initDatabaseConnection: initUserDatabaseConnection } = require('./routes/user.cjs');

// 加载根目录的 .env 文件
dotenv.config({ path: path.resolve(process.cwd(), '.env') });

// 设置数据库连接环境变量
process.env.PG_USER = process.env.PG_USER || 'root';
process.env.PG_PASSWORD = process.env.PG_PASSWORD || 'Letusdoit000';
process.env.PG_HOST = process.env.PG_HOST || 'localhost'; // 使用localhost而不是db
process.env.PG_PORT = process.env.PG_PORT || '5432';
process.env.PG_DATABASE = process.env.PG_DATABASE || 'app';

// console.log('环境变量已设置:', {
//   PG_USER: process.env.PG_USER,
//   PG_HOST: process.env.PG_HOST,
//   PG_DATABASE: process.env.PG_DATABASE,
//   PG_PORT: process.env.PG_PORT,
//   PG_PASSWORD: process.env.PG_PASSWORD ? '已设置' : '未设置'
// });
// 在设置环境变量后初始化数据库连接
initDatabaseConnection();
initFileDatabaseConnection();
// initUserDatabaseConnection();
const app = express();
let PORT = process.env.PORT || 3003;
// 中间件
app.use(cors({
  origin: ['http://localhost:5177', 'http://localhost:5173', 'http://127.0.0.1:5173'], // 添加所有可能的前端地址
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'Accept']
}));
app.use(express.json());
// 路由
app.use('/api/auth', authRoutes);
app.use('/api/files', fileRoutes); // 添加文件路由
app.use('/api/people', peopleRoutes);
// app.use('/api/users', userRoutes);
// 添加用户管理路由
app.get('/api/users', async (req, res) => {
  try {
    const auth = require('./routes/auth.cjs');
    if (!auth.pool()) {
      return res.status(500).json({ message: '数据库未连接' });
    }
    const result = await auth.pool().query('SELECT id, username, created_at FROM users');
    res.json(result.rows);
  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).json({ message: '获取用户列表失败' });
  }
});
// 删除用户的路由
app.delete('/api/users/:id', async (req, res) => {
  console.log(`收到删除用户请求，ID: ${req.params.id}`);
  
  try {
    const { id } = req.params;
    const auth = require('./routes/auth.cjs');
    const pool = auth.pool();
    
    if (!pool) {
      console.log('数据库未连接，删除操作终止');
      return res.status(500).json({ message: '数据库未连接' });
    }
    // 先检查用户是否存在
    const checkUser = await pool.query('SELECT id FROM users WHERE id = $1', [id]);
    if (checkUser.rows.length === 0) {
      console.log(`用户ID:${id} 不存在，返回404错误`);
      return res.status(404).json({ message: '用户不存在' });
    }
    // 执行删除操作
    const deleteResult = await pool.query('DELETE FROM users WHERE id = $1', [id]);
    // 记录操作日志
    console.log(`用户ID ${id} 已被删除，时间: ${new Date().toISOString()}`);
    res.json({ 
      message: '用户删除成功',
      userId: id,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    console.error('删除用户失败:', error);
    // 检查是否为外键约束错误
    if (error.code === '23503') {
      return res.status(400).json({ 
        message: '无法删除此用户，因为它与其他数据相关联',
        error: error.message
      });
    }
    res.status(500).json({ 
      message: '删除用户失败', 
      error: error.message 
    });
  }
});
// 添加批量删除用户的路由
app.post('/api/users/batch-delete', async (req, res) => {
  try {
    const { ids } = req.body;
    
    if (!Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({ message: '无效的用户ID列表' });
    }
    
    const auth = require('./routes/auth.cjs');
    const pool = auth.pool();
    
    if (!pool) {
      return res.status(500).json({ message: '数据库未连接' });
    }
    
    // 使用 IN 操作符批量删除
    const result = await pool.query(
      'DELETE FROM users WHERE id = ANY($1::int[]) RETURNING id', 
      [ids]
    );
    
    console.log(`已批量删除 ${result.rowCount} 个用户，时间: ${new Date().toISOString()}`);
    
    res.json({ 
      message: `成功删除 ${result.rowCount} 个用户`,
      deletedCount: result.rowCount,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    console.error('批量删除用户失败:', error);
    res.status(500).json({ 
      message: '批量删除用户失败', 
      error: error.message 
    });
  }
});
// 添加支持服务器端分页、排序和过滤的接口
app.post('/api/users/search', async (req, res) => {
  try {
    const { page = 1, pageSize = 10, sortModel = [], filterModel = {} } = req.body;
    const auth = require('./routes/auth.cjs');
    if (!auth.pool()) {
      return res.status(500).json({ message: '数据库未连接' });
    }
    
    // 构建查询
    let query = 'SELECT id, username, email, created_at FROM users';
    let countQuery = 'SELECT COUNT(*) FROM users';
    const queryParams = [];
    let whereClause = '';
    
    // 添加过滤条件
    if (Object.keys(filterModel).length > 0) {
      const filters = [];
      Object.entries(filterModel).forEach(([field, filter]) => {
        if (filter.filter) {
          queryParams.push(`%${filter.filter}%`);
          filters.push(`${field} ILIKE $${queryParams.length}`);
        }
      });
      
      if (filters.length > 0) {
        whereClause = ` WHERE ${filters.join(' AND ')}`;
      }
    }
    
    // 添加WHERE子句到查询和计数查询
    query += whereClause;
    countQuery += whereClause;
    
    // 添加排序
    if (sortModel.length > 0) {
      const sortFields = sortModel.map(sort => 
        `${sort.field} ${sort.sort.toUpperCase()}`
      );
      query += ` ORDER BY ${sortFields.join(', ')}`;
    } else {
      query += ' ORDER BY id ASC';  // 默认排序
    }
    
    // 添加分页
    const offset = (page - 1) * pageSize;
    query += ` LIMIT ${pageSize} OFFSET ${offset}`;
    
    // 执行查询
    const [dataResult, countResult] = await Promise.all([
      auth.pool().query(query, queryParams),
      auth.pool().query(countQuery, queryParams)
    ]);
    
    // 返回结果
    res.json({
      rows: dataResult.rows,
      total: parseInt(countResult.rows[0].count)
    });
  } catch (error) {
    console.error('搜索用户失败:', error);
    res.status(500).json({ message: '搜索用户失败' });
  }
});
// 测试路由
app.get('/api/test', (req, res) => {
  res.json({ message: '服务器正常工作' });
});

// 健康检查接口
app.get('/api/health', (req, res) => {
  res.json({ 
    status: 'ok', 
    timestamp: new Date().toISOString(),
    routes: [
      { path: '/api/auth/login', method: 'POST' },
      { path: '/api/auth/register', method: 'POST' },
      { path: '/api/test', method: 'GET' },
      { path: '/api/users', method: 'GET' },
      { path: '/api/users/:id', method: 'DELETE' },
      { path: '/api/users/search', method: 'POST' },
      { path: '/api/users/batch-delete', method: 'POST' },
      { path: '/api/files', method: 'GET' },
      { path: '/api/files/:id', method: 'DELETE' },
      { path: '/api/files/upload', method: 'POST' },
      { path: '/api/files/download/:id', method: 'GET' },
      { path: '/api/people', method: 'GET' },
      { path: '/api/people', method: 'POST' },
      { path: '/api/people/:id', method: 'PUT' },
      { path: '/api/people/:id', method: 'DELETE' },
      { path: '/api/people/search', method: 'POST' }
    ]
  });
});
// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ message: '服务器内部错误' });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
}); 